﻿using AutoMapper;
using MediatR;
using Reporting.API.Application.Commands.ProductionPlans;
using Reporting.Domain;
using Reporting.Errorcode;
using Reporting.Errorcode.ErrorCode;
using Reporting.Infrastructure.Interfaces.ProductionPlans;

namespace Reporting.API.Application.CommandHandler.ProductionPlans
{
    public class AddProductionPlanCommandHandler : IRequestHandler<AddProductionPlanCommand, ApiResult>
    {
        private readonly IProductionPlanRepository _productionPlanRepository;
        private readonly IMapper _mapper;
        private readonly ILogger<AddProductionPlanCommandHandler> _logger;

        public AddProductionPlanCommandHandler(ILogger<AddProductionPlanCommandHandler> logger, IMapper mapper, IProductionPlanRepository productionPlanRepository)
        {
            _logger = logger;
            _mapper = mapper;
            _productionPlanRepository = productionPlanRepository;
        }

        public async Task<ApiResult> Handle(AddProductionPlanCommand request, CancellationToken cancellationToken)
        {
            try
            {
                // 将 DTO 映射为实体类
                var userEntity = _mapper.Map<ProductionPlan>(request);

                // 调用仓储层添加用户
                var addedUser = await _productionPlanRepository.InsertAsync(userEntity);

                // 返回成功结果  StatusCodeEnum
                return ApiResult.Success(StatusCodeEnum.Success);
            }
            catch (Exception ex)
            {
                 _logger.LogError(ex, "生产计划添加失败");
                throw;
            }
            
        }
    }
}
